/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package horizon.states;

import horizon.graphics.RenderingContext;
import horizon.util.InputManager;
import java.util.ConcurrentModificationException;
import java.util.ListIterator;
import java.util.Stack;

public class StateManager {

    public Stack<State> states = new Stack();
    static StateManager instance;
    State nextToPush = null;

    public StateManager() {
        instance = this;
    }

    public static StateManager getInstance() {
        return instance;
    }

    public void update(long elapsedTime) {
        if (nextToPush != null) {
            states.push(nextToPush);
            nextToPush = null;
        }

        

        ListIterator<State> it = states.listIterator();

        try {
            while (it.hasNext()) {
                State s = it.next();

                if (s.active) {

                    s.update(elapsedTime);

                }

            }
        } catch (ConcurrentModificationException e) {
        }

    }

    public void render(RenderingContext r) {


        ListIterator<State> it = states.listIterator();

        while (it.hasNext()) {
            State s = it.next();

            if (s.active) {

                s.render(r);

            }

        }



    }

    public void pushState(State s) {

        s.init();
        //states.push(s);
        nextToPush = s;
        InputManager.getInstance().setBlocked(false);

    }

    public void pushAndRemovePrevious(State s) {

        s.init();
        states.pop();

        nextToPush = s;
        InputManager.getInstance().setBlocked(false);

    }

    public State getState(Class c) {

        for (State s : states) {

            if (c.isInstance(s)) {

                return s;

            }

        }

        return null;
    }
}
